import Vuex, {ActionTree, Module, MutationTree} from "vuex";
import {getTaskStatus} from "@/services/liank";
import tips from "@/utils/tips";

export interface State {
    previewFileImageList: any[],
}

interface LoadingParams {
    title: string;
    printerState: boolean;
    isRefund: number;
    failReason: string;
}

const state: any = {
    previewFileImageList: {
        imageList: [],
        taskTicket: ''
    },
    loadingParams: {
        title: '', // 当前状态标题
        printerState: false, // 打印机状态
        isRefund: 0, // 当前 是否退款
        failReason: '' // 失败原因
    }
}

let interval: any = null;

const mutations: MutationTree<any> = {
    // 预览文件列表
    setPreviewFileImageList(state, payload: { imageList: string[], taskTicket: string }): void {
        state.previewFileImageList = payload;
    },
    // 预览文件列表清空
    clearPreviewFileImageList(state): void {
        state.previewFileImageList = [];
    },

    // 加载参数
    setLoadingParams(state, payload: Partial<LoadingParams>) {
        state.loadingParams = payload
    }
}

const actions: ActionTree<State, any> = {
    // 循环停止
    clearInterval() {
        if (interval) {
            clearInterval(interval)
            interval = null;
        }
    },

    // 打印任务监控
    async monitorPrintTask({commit}, {printParams, lang, orderId}) {
        if (!orderId) commit("clearPreviewFileImageList");
        // 为了避免初始 1
        commit('setLoadingParams', {title: lang.printer_state_text.READY, printerState: false, isRefund: 0});

        console.log("print_file.ts 打印任务监控", printParams, lang, orderId);
        const {deviceId, deviceKey, devicePort, taskId} = printParams;
        let hasRedirected = false;

        interval = setInterval(async () => {
            const res = await getTaskStatus(deviceId, deviceKey, devicePort, taskId);
            const {task_state, task_result} = res.data;
            console.log("print_file.ts 打印任务监控", task_state, task_result);

            // ھالەت يېڭىلاش
            switch (task_state) {
                case 'READY': // 准备中
                    commit('setLoadingParams', {
                        title: lang.printer_state_text.READY, printerState: false, isRefund: 0
                    });
                    break;
                case 'PARSING': // 解析中
                    commit('setLoadingParams', {
                        title: lang.printer_state_text.PARSING, printerState: false, isRefund: 0
                    });
                    break;
                case 'SENDING': // 发送中
                    commit('setLoadingParams', {
                        title: lang.printer_state_text.SENDING, printerState: false, isRefund: 0
                    });
                    break;
                case 'SUCCESS': // 成功
                    if (task_result?.code === 200) {
                        commit('setLoadingParams', {
                            title: lang.printer_state_text.SUCCESS, printerState: true, isRefund: 1
                        });
                    } else {
                        tips.toast(task_result.msg, 4000);
                        commit('setLoadingParams', {
                            title: lang.printer_state_text.FAILURE,
                            printerState: true, isRefund: 2, failReason: task_result.msg
                        });
                    }
                    clearInterval(interval);
                    break;
                case 'FAILURE': // 失败
                    commit('setLoadingParams', {
                        title: lang.printer_state_text.FAILURE,
                        printerState: true, isRefund: 2, failReason: task_result.msg
                    });
                    clearInterval(interval);
                    break;
                case 'SET_REVOKE': // 标记为撤回
                    clearInterval(interval);
                    break
                case 'REVOKED': // 撤回成功
                    clearInterval(interval);
                    break
            }

            if (task_result?.code === 200) {
                const {data: {img_list = [], taskTicket = ''}} = task_result;

                // 预览模式
                if (!orderId && img_list?.length) {
                    if (!hasRedirected) {
                        hasRedirected = true;
                        commit("setPreviewFileImageList", {imageList: img_list, taskTicket});
                        // 跳转到预览页面
                        uni.redirectTo({
                            url: `/pages/file/print_preview?params=${encodeURIComponent(JSON.stringify({printParams}))}`
                        });
                    } else {
                        // 继续请求获取的其他 imageList
                        commit("setPreviewFileImageList", {imageList: img_list, taskTicket});
                    }
                }
            }
        }, 2000);
    }
}


const PrintModule: Module<State, any> = {
    namespaced: true,
    state,
    mutations,
    actions,
};

export default PrintModule;